package com.alumni_circle.core.config;

import com.alumni_circle.core.filter.CustomAuthenticationFilter;
import com.alumni_circle.core.filter.JwtAuthenticationTokenFilter;
import com.alumni_circle.core.security.*;
import com.alumni_circle.core.utils.RsaUtils;
import com.alumni_circle.service.security.impl.UserSecurityServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * @author 龙小虬
 * @since 2020-08-06 17:56
 */
@Component
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //自定义登录验证
    @Resource
    UserSecurityServiceImpl userSecurityService;

    /**
     * 登录成功
     */
    @Resource
    SuccessHandler successHandler;

    //登录失败
    @Resource
    FailHandler failHandler;

    //无权限
    @Resource
    PermissionDeniedHandler permissionDeniedHandler;

    //未登录
    @Resource
    NoLoginHandler noLoginHandler;

    //注销成功
    @Resource
    SuccessLogoutHandler successLogoutHandler;

    //jwt验证
    @Resource
    JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Resource
    WeChatAuthenticationProvider weChatAuthenticationProvider;

    @Bean
    DaoAuthenticationProvider daoAuthenticationProvider(){
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setPasswordEncoder(new RsaUtils());
        daoAuthenticationProvider.setUserDetailsService(userSecurityService);
        return daoAuthenticationProvider;
    }

    @Override
    protected AuthenticationManager authenticationManager() throws Exception{
        ProviderManager providerManager = new ProviderManager(Arrays.asList(weChatAuthenticationProvider,daoAuthenticationProvider()));
        providerManager.setEraseCredentialsAfterAuthentication(false);
        return providerManager;

    }

    @Autowired
    public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder.userDetailsService(userSecurityService).passwordEncoder(new RsaUtils());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //关闭csrf
                .csrf().disable()
                //无权限
                .exceptionHandling().accessDeniedHandler(permissionDeniedHandler)
                .and()
                //关闭session，开启无状态访问
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                //未登录返回
                .httpBasic().authenticationEntryPoint(noLoginHandler)
                .and()
                //所有的都要进行登录验证
                .authorizeRequests()
                //放行"/login"
                .antMatchers("/login",
                        "/swagger-ui.html",
                        "/swagger-resources/**",
                        "/images/**",
                        "/webjars/**",
                        "/v2/api-docs",
                        "/swagger/**",
                        "/*/api-docs").permitAll()
                //除了上面的请求，其他请求全部需要验证
                .anyRequest().authenticated()
                .and()
                //设置jsp使用loginPage   设置接口使用loginProcessingUrl
//                .formLogin().loginProcessingUrl("/login")
                .formLogin().loginPage("/")
                //登录成功返回
                .successHandler(successHandler)
                //登录失败返回
                .failureHandler(failHandler)
                .and()
                .logout().permitAll()
                //退出成功返回
                .logoutSuccessHandler(successLogoutHandler);
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        http.addFilterAt(customAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

    @Bean
    CustomAuthenticationFilter customAuthenticationFilter() throws Exception {
        CustomAuthenticationFilter filter = new CustomAuthenticationFilter();
        filter.setAuthenticationSuccessHandler(new SuccessHandler());
        filter.setAuthenticationFailureHandler(new FailHandler());
        filter.setFilterProcessesUrl("/login");

        //这句很关键，重用WebSecurityConfigurerAdapter配置的AuthenticationManager，不然要自己组装AuthenticationManager
        filter.setAuthenticationManager(authenticationManagerBean());
        return filter;
    }
}
